package com.syl.auth.handle;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.syl.auth.utils.SecurityUtil;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * @ClassName SmallAccessDeniedHandler
 * @Description 授权被拒绝处理器
 * @Author YunLong
 * @Date 2023/5/3 11:13
 */
public class SmallAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        HashMap<String, Object> result = new HashMap<>();
        result.put("code", SecurityUtil.permissionDeniedCode);
        result.put("msg", accessDeniedException.getMessage());
        out.write(new ObjectMapper().writeValueAsString(result));
        out.flush();
        out.close();
    }
}
